<template>
  <div class="app-container chat-container">
    <el-container class="chat-layout">
      <!-- 吃药提醒区域 -->
      <el-main class="reminder-list" ref="reminderList">
        <div v-if="reminderList.length > 0">
          <h2>今天的吃药提醒</h2>
          <el-card
            v-for="(reminder, index) in reminderList"
            :key="index"
            class="reminder-item"
            :class="{'reminder-soon': reminder.status === 'soon', 'reminder-upcoming': reminder.status === 'upcoming', 'reminder-past': reminder.status === 'past'}"
          >
            <div class="reminder-content">
              <h3>{{ reminder.symptom }}</h3>
              <p>药品名称:
                <!-- 修改为显示药品实际名称 -->
                {{ getMedicineName(reminder.medicineName) }}
              </p>
              <p>提醒时间: {{ reminder.reminderTime }}</p>
              <p>提前提醒时间: {{ reminder.advanceReminderTime }} 分钟</p>
            </div>
            <el-button @click="openReportDialog(reminder)">填报</el-button>
          </el-card>
        </div>
        <div v-else>
          <h2>今天没有吃药提醒</h2>
        </div>
      </el-main>
    </el-container>
    <!-- 吃药确认弹窗 -->
    <el-dialog
      :visible.sync="confirmDialogVisible"
      title="吃药确认"
      @close="closeConfirmDialog"
    >
      <span>是否已经吃药</span>
      <template #footer>
        <span>
          <el-button @click="confirmDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmTakingMedicine">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 填报弹窗 -->
    <el-dialog
      :visible.sync="reportDialogVisible"
      title="用药信息填报"
      @close="closeReportDialog"
    >
      <el-form :model="reportForm" ref="reportFormRef" :rules="reportRules">
        <el-form-item label="药品名称">
          <el-input v-model="reportForm.medicineId" readonly></el-input>
        </el-form-item>
        <el-form-item label="用药人" prop="user">
          <el-input v-model="reportForm.userId" placeholder="请输入用药人姓名"></el-input>
        </el-form-item>
        <el-form-item label="用药时间" prop="time">
          <el-date-picker
            v-model="reportForm.medicationTime"
            type="datetime"
            placeholder="请选择用药时间"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="reportDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReport">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listReminder2 } from "@/api/system/reminder";
import { questionHome } from "@/api/system/report";
import moment from 'moment';
import {addMedicine, addUseMedicineRecord} from "@/api/system/medicine";

export default {
  name: "ChatPage",
  dicts: ['yaopin', 'tixing'], // 确保这里引入了药品字典
  data() {
    return {
      reminderList: [],
      messages: [
        {
          type: 'bot',
          content: '您好！我是JS代码生成助手，请输入您的需求，我会生成JS代码',
          time: this.formatTime(new Date())
        }
      ],
      inputMessage: '',
      sending: false,
      confirmDialogVisible: false, // 吃药确认弹窗是否可见
      currentReminder: {}, // 当前提醒信息
      reportDialogVisible: false, // 填报弹窗是否可见
      reportForm: {
        medicineName: '',
        user: '',
        time: null
      },
      currentReportReminder: {}, // 当前要填报的提醒信息
      reportRules: {
        userId: [
          { required: true, message: '请输入用药人姓名', trigger: 'blur' }
        ],
        medicationTime: [
          { required: true, message: '请选择用药时间', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    this.getTodayReminders();
    this.startReminderTimer();
  },
  methods: {
    /** 获取当天的吃药提醒 */
    getTodayReminders() {
      listReminder2({}).then(response => {
        this.reminderList = response.rows;
        this.updateReminderStatus();
      }).catch(error => {
        console.error("获取当天吃药提醒失败:", error);
      });
    },

    /** 更新提醒项的状态 */
    updateReminderStatus() {
      const pastReminders = [];
      this.reminderList.forEach(reminder => {
        const todayDate = moment().format('YYYY-MM-DD'); // 获取当天的日期
        const reminderTime = moment(`${todayDate} ${reminder.reminderTime}`, 'YYYY-MM-DD HH:mm');
        const currentTime = moment();
        const fiveMinutesBefore = reminderTime.clone().subtract(5, 'minutes');

        if (currentTime.isAfter(reminderTime)) {
          reminder.status = 'past';
          pastReminders.push(reminder);
        } else if (currentTime.isAfter(fiveMinutesBefore) && currentTime.isBefore(reminderTime)) {
          reminder.status = 'soon';
          if (!reminder.confirmed) {
            this.currentReminder = reminder;
            this.confirmDialogVisible = true;
            reminder.confirmed = true; // 标记为已弹出确认框
          }
        } else {
          reminder.status = 'upcoming';
        }
      });

      if (pastReminders.length > 0) {
        pastReminders.forEach(reminder => {
          ElMessage.warning(`您该吃 ${this.getMedicineName(reminder.medicineName)} 了，针对症状：${reminder.symptom}`);
        });
      }
    },

    /** 定时更新提醒状态 */
    startReminderTimer() {
      setInterval(() => {
        this.updateReminderStatus();
      }, 60000); // 每分钟更新一次
    },

    async handleSend() {
      if (!this.inputMessage.trim()) return;

      // 添加用户消息
      const userMessage = {
        type: 'user',
        content: this.inputMessage,
        time: this.formatTime(new Date())
      };
      this.messages.push(userMessage);

      // 模拟发送请求
      try {
        this.sending = true;
        const botResponse = await this.getBotResponse(this.inputMessage);

        // 添加机器人回复
        this.messages.push({
          type: 'bot',
          content: botResponse,
          time: this.formatTime(new Date())
        });
      } finally {
        this.sending = false;
        this.inputMessage = '';
        this.scrollToBottom();
      }
    },

    // 调用后端接口获取报告内容
    async getBotResponse(input) {
      return questionHome({ caseName: input }).then(response => {
        console.log(response);
        console.log(response.data);
        return response.data;
      });
    },

    formatTime(date) {
      return `${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messageList;
        if (container) {
          container.$el.scrollTop = container.$el.scrollHeight;
        }
      });
    },

    // 关闭吃药确认弹窗
    closeConfirmDialog() {
      this.confirmDialogVisible = false;
    },

    // 确认吃药
    confirmTakingMedicine() {
      this.confirmDialogVisible = false;
      // 标记该提醒已完成
      console.log(`已确认吃了 ${this.getMedicineName(this.currentReminder.medicineName)}`);
    },

    // 打开填报弹窗
    openReportDialog(reminder) {
      this.currentReportReminder = reminder;
      this.reportForm.medicineId = this.getMedicineName(reminder.medicineName);
      this.reportDialogVisible = true;
    },

    // 关闭填报弹窗
    closeReportDialog() {
      this.reportDialogVisible = false;
      this.reportForm = {
        medicineName: '',
        user: '',
        time: null
      };
    },

    // 提交填报信息
    submitReport() {
      this.$refs.reportFormRef.validate((valid) => {
        if (valid) {
          addUseMedicineRecord(this.reportForm).then(response => {
            this.$modal.msgSuccess("填报成功");
            this.reportDialogVisible = false;
          });
          console.log(`已填报 ${this.reportForm.medicineName} 的用药信息：`, this.reportForm);
          this.reportForm = {
            medicineId: '',
            userId: '',
            medicationTime: null
          };
        } else {
          console.log('请填写完整的用药信息');
          return false;
        }
      });
    },

    // 根据药品 ID 获取药品名称
    getMedicineName(medicineId) {
      const medicineDict = this.dict.type.yaopin.find(item => item.value === medicineId);
      return medicineDict ? medicineDict.label : medicineId;
    }
  }
};
</script>

<style scoped lang="scss">
.chat-container {
  height: 100vh;
  background: #f5f6fa;
  padding: 0 !important;

  .chat-layout {
    height: 100%;
    max-width: 1200px;
    margin: 0 auto;
    background: white;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    display: flex;
    flex-direction: column;
  }

  .reminder-list {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background: #f8f9fb;
    display: flex;
    flex-direction: column;
    gap: 15px;

    h2 {
      font-size: 20px;
      margin-bottom: 20px;
    }

    .reminder-item {
      width: 100%;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

      .reminder-content {
        padding: 16px;

        h3 {
          font-size: 16px;
          margin-bottom: 10px;
        }

        p {
          font-size: 14px;
          line-height: 1.6;
          margin-bottom: 5px;
        }
      }
    }

    .reminder-soon {
      border-left: 4px solid red;
      background-color: #ffebee;

      .reminder-content {
        color: red;
      }
    }

    .reminder-upcoming {
      border-left: 4px solid #4caf50;
      background-color: #e8f5e9;

      .reminder-content {
        color: #4caf50;
      }
    }

    .reminder-past {
      border-left: 4px solid #9e9e9e;
      background-color: #f5f5f5;

      .reminder-content {
        color: #9e9e9e;
      }
    }
  }

  .message-list {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background: #f8f9fb;
    display: flex;
    flex-direction: column;
    gap: 15px;

    .message-item {
      display: flex;
      max-width: 80%;

      &.user {
        align-self: flex-end;

        .message-bubble {
          background: #409eff;
          color: white;
          border-radius: 12px 12px 0 12px;

          &::after {
            right: -8px;
            border-color: transparent transparent #409eff #409eff;
          }
        }
      }

      &.bot {
        align-self: flex-start;

        .message-bubble {
          background: #e8f4ff;
          color: #333;
          border-radius: 12px 12px 12px 0;

          &::after {
            left: -8px;
            border-color: transparent #e8f4ff #e8f4ff transparent;
          }
        }
      }

      .message-bubble {
        position: relative;
        padding: 12px 16px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          width: 0;
          height: 0;
          border-style: solid;
          border-width: 8px 0 0 8px;
        }

        .message-content {
          font-size: 14px;
          line-height: 1.6;
          white-space: pre-wrap;
          word-break: break-word;
        }

        .message-time {
          margin-top: 6px;
          font-size: 12px;
          color: rgba(97, 90, 90, 0.8);
          text-align: right;

          &.bot {
            color: rgba(0, 0, 0, 0.5);
          }
        }
      }
    }
  }

  .input-area {
    border-top: 20px solid #eee;
    padding: 20px;
    background: white;

    .input-wrapper {
      display: flex;
      gap: 12px;
      align-items: flex-end;

      .message-input {
        flex: 1;

        ::v-deep .el-textarea__inner {
          border-radius: 8px;
          padding: 12px;
          font-size: 14px;
          line-height: 1.6;
        }
      }

      .send-button {
        height: 74px;
        padding: 0 28px;
        border-radius: 8px;
        font-weight: 500;
      }
    }
  }
}
</style>
